package com.cdivtc.management;

import com.cdivtc.management.pojo.User;
import com.cdivtc.management.service.UserSerive;
import com.cdivtc.management.shiro.JwtToken;
import com.cdivtc.management.utils.JwtUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;


import java.util.List;

public class AuthRealm extends AuthorizingRealm {
    @Autowired
    private UserSerive service;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }
    //    授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        List<String> roleSet = JwtUtil.getRole(principalCollection.toString());


        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        if(roleSet!=null)
        info.addRoles(roleSet);

        return info;
    }

    //认证登录
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String tokens = (String) token.getCredentials();

        boolean verify = JwtUtil.verify(tokens);
        if(!verify)
            throw  new AuthenticationException("权限解析异常");

        String username = JwtUtil.getUsername(tokens);
        System.out.println("username = " + username);
        User user = service.findByUid(username);
        if (user == null) {
            throw new IllegalArgumentException("用户不存在");
        }

        System.out.println("tokens =AuthenticationInfo " + tokens);
        return new SimpleAuthenticationInfo(tokens, tokens, this.getClass().getName());
    }
}
